package org.abc.fund.service.auth;

import org.abc.fund.entity.user.User;
import org.abc.fund.repository.user.UserRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Optional;

@Service
public class AuthService {

  private final UserRepository userRepository;

  public AuthService(UserRepository userRepository) {
    this.userRepository = userRepository;
  }

  /**
   * 用户登录认证逻辑
   *
   * @param username 用户名
   * @param rawPassword 原始密码
   * @return 如果认证成功，返回包含用户信息的Optional；否则返回空的Optional
   */
  @Transactional(readOnly = true)
  public Optional<User> authenticate(String username, String rawPassword) {
    Optional<User> userOptional = userRepository.findByUsername(username);

    if (userOptional.isPresent()) {
      User user = userOptional.get();
      // 直接比对明文密码
      if (user.getPassword().equals(rawPassword)) {
        return Optional.of(user);
      }
    }

    // 用户不存在或密码不匹配，则返回空
    return Optional.empty();
  }
}
